package com.wanlink.mall.http.rxhelper;

import com.wanlink.mall.http.Exception.ApiException;
import com.wanlink.mall.http.response.BaseResponse;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;

;

/**
 * user：chenqm
 * desc：Rx处理服务器返回,
 * 服务器的返回的数据格式一般都是一致的，所有我们每个网络请求都可以使
 * 用compose(RxResultHelper.handleResult())来处理服务器返回，一般服务器返回成功码为200，
 * 相应改一下返回码的判断就行了
 */

public class RxResultHelper {

    private static final int RESPONSE_SUCCESS_CODE = 200; //大部分为200
    private static final int RESPONSE_ERROR_CODE = -1;

    public static <T> ObservableTransformer<BaseResponse<T>, T> handleResult() {
        return new ObservableTransformer<BaseResponse<T>, T>() {
            @Override
            public ObservableSource<T> apply(Observable<BaseResponse<T>> tObservable) {
                return tObservable.flatMap(
                        new Function<BaseResponse<T>, Observable<T>>() {
                            @Override
                            public Observable<T> apply(BaseResponse<T> BaseResponse) throws Exception {
                                int code = BaseResponse.getCode();
                                if (code == RESPONSE_SUCCESS_CODE) {
                                    return Observable.just(BaseResponse.getData());
                                } else {
                                    ApiException exception = new ApiException(BaseResponse.getCode(), BaseResponse.getMsg());
                                    return Observable.error(exception);
                                }
                            }
                        }
                );
            }

        };
    }

}
